import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {SearchService} from '../movie/search-service/search.service';
import {userDetails, UserService, userStatus} from '../user/service/user.service';
import {UserDetails} from '../user/UserDetails';

export class UserAccount {
  username: string;
  password: string;
  email: string;

  constructor(username: string = '', password: string = '', email: string = '') {
    this.username = username;
    this.password = password;
    this.email = email;
  }
}

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
  providers: [SearchService, UserService],
})
export class HeaderComponent implements OnInit {
  queryStr: string;
  username = 'user';
  password = 'init_user';
  userDetails: UserDetails;
  userStatus = {'isLogin': false, 'uid': ''};
  regUser: UserAccount = new UserAccount();
  recheckPwd = '';

  constructor(private route: Router, private activatedRoute: ActivatedRoute, private searchService: SearchService,
              private userService: UserService) {
    this.userDetails = userDetails;
    this.userStatus = userStatus;
  }

  ngOnInit() {
    const uid: string = localStorage.getItem('uid');
    if (uid === undefined || uid === null || uid.length === 0) {
      return;
    }
    this.userService.getUserInfo();
    userStatus.isLogin = true;
    userStatus.uid = uid;
  }

  onKeyUp(event) {
    if (event.which === 13) {
      if (this.queryStr === undefined || this.queryStr == null || this.queryStr.length === 0) {
        return;
      }
      this.route.navigate(['/movie/search']);
      this.searchService.search(this.queryStr);
      this.searchService.analyzeField(this.queryStr);
    }
  }

  login() {
    if (this.username.length === 0 || this.password.length === 0) {
      alert('用户名或者密码不能为空');
      return;
    }
    this.userService.login2(this.username, this.password);
  }

  register() {
    if (this.regUser.username.length < 4) {
      alert('用户名长度不能小于4');
      return;
    }
    if (this.regUser.password.length < 4) {
      alert('用户名密码长度不能小于4');
      return;
    } else if (this.regUser.password !== this.recheckPwd) {
      alert('两次输入的密码不一致');
      return;
    }
    const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    if (!emailReg.test(this.regUser.email)) {
      alert('邮箱格式不正确');
      return;
    }
    this.userService.register(this.regUser);
  }

  forgetPwd() {

  }

  logout() {
    this.userService.logout();
  }

  routeToUserHome() {
    this.route.navigateByUrl('/user/(userHome:favorite)');
  }
}
